package com.atelier.plugin.database.domain;

import com.atelier.plugin.database.ui.DataBaseToolWindowContent;
import com.atelier.plugin.database.ui.DataSourceSettingDialog;
import com.atelier.plugin.database.util.ConnectionInfoTreeUtil;
import com.atelier.plugin.database.util.ConnectionUtil;
import com.atelier.plugin.database.util.PasswordStorageUtil;
import com.atelier.plugin.service.DataBaseConnectionStorageService;
import com.atelier.plugin.tool.ProjectUtils;
import com.atelier.plugin.tool.StringUtils;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import net.sf.cglib.beans.BeanCopier;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class DataSourceSettingConfigurable implements Configurable {
    public static Logger LOGGER = LoggerFactory.getLogger(DataSourceSettingConfigurable.class);
    private JComponent panel;

    @Nls(capitalization = Nls.Capitalization.Title)
    @Override
    public String getDisplayName() {
        return MyDatabaseBundle.message("configurable.DataSourceManagerDialog.MyConfigurable.display.name"); // 显示在设置对话框中的标题
    }

    @Nullable
    @Override
    public JComponent createComponent() {
        if (panel == null) {
            panel =  DataSourceSettingDialog.getInstance().getRootPane(); // 创建一个面板来配置数据源设置
        }
        return panel;
    }

    @Override
    public boolean isModified() {
        DefaultListModel<DatabaseConnectionInfo> listModel = DataSourceSettingDialog.getInstance().getListModel();
        List<DatabaseConnectionInfo> connectionInfos = DataBaseConnectionStorageService.getInstance(ProjectUtils.getCurrProject()).getConnectionInfos();

        // 比较配置对话框中的设置与数据源中的设置是否不同
        if (listModel.getSize() != connectionInfos.size()) {
            return true;
        }

        for (int i = 0; i < listModel.getSize(); i++) {

            DatabaseConnectionInfo dialogInfo = listModel.getElementAt(i);
            DatabaseConnectionInfo dataSourceInfo = connectionInfos.get(i);

            // 比较具体的配置属性，例如用户名、密码、主机等
            if (!dialogInfo.equals(dataSourceInfo)) {
                return true;
            }
        }

        return false; // 没有更改
    }

    /**
     *
     */
    @Override
    public void apply() throws ConfigurationException {
        DefaultListModel<DatabaseConnectionInfo> listModel = DataSourceSettingDialog.getInstance().getListModel();
        List<DatabaseConnectionInfo> connectionInfoList = new ArrayList<>(Collections.list(listModel.elements()));
        DataBaseConnectionStorageService instance = DataBaseConnectionStorageService.getInstance(ProjectUtils.getCurrProject());
        ArrayList<DatabaseConnectionInfo> databaseConnectionInfos = new ArrayList<>();
        for (DatabaseConnectionInfo connectionInfo : connectionInfoList) {
            DatabaseConnectionInfo newConnectionInfo = new DatabaseConnectionInfo();
            BeanCopier beanCopier = BeanCopier.create(DatabaseConnectionInfo.class, DatabaseConnectionInfo.class, false);
            beanCopier.copy(connectionInfo, newConnectionInfo, null);

            try {
                newConnectionInfo.setState(ConnectionUtil.getInstance(newConnectionInfo).testConnection());
            } catch (Exception e) {
                newConnectionInfo.setState(false);
//                throw new RuntimeException(e);
            LOGGER.error(e.getMessage());
            } finally {
                databaseConnectionInfos.add(newConnectionInfo);
            }
        }
        // 使用 ProgressManager 显示进度条
        ProgressManager progressManager = ProgressManager.getInstance();
        progressManager.run(new Task.Backgroundable(ProjectUtils.getCurrProject(), "Saving Data Source Configurations") {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                // 在这里执行保存操作
                instance.mergeAndClearConnectionInfos(databaseConnectionInfos);
                JTree databaseTree = null;
                try {
                    databaseTree = DataBaseToolWindowContent.getInstants().getDatabaseTree();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                try {
                    ConnectionInfoTreeUtil.refreshTree(databaseTree);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

}
